package com.thinksns.sociax.t4.android.event;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.model.Text;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.android.R;
import com.thinksns.sociax.t4.android.popupwindow.EventEditPopupWindow;
import com.thinksns.sociax.t4.component.SmallDialog;
import com.thinksns.sociax.t4.util.LogUtils;

import java.util.List;

/**
 * Created by zhiyicx on 2017/5/5.
 */

public class EventLocationActivity extends ThinksnsAbscractActivity implements View.OnClickListener, LocationSource, AMap.OnMapClickListener, AMap.OnMapLoadedListener, AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener, AMap.OnInfoWindowClickListener {

    public static final int LOCATION_RESULT = 1201;

    private MapView location_map;
    private ImageView iv_back;
    private TextView save_tv;
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private GeocodeSearch geocoderSearch;
    private Marker marker;
    private String address;
    private String area;
    private String city;
    private String place;
    private String longtitude;
    private String latitude;
    private EventEditPopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreateNoTitle(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initView();
        location_map.onCreate(savedInstanceState);// 必须要写
        initData();

    }

    private void initView(){
        location_map = (MapView) findViewById(R.id.location_map);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        save_tv = (TextView) findViewById(R.id.save_tv);
        iv_back.setOnClickListener(this);
        save_tv.setOnClickListener(this);
    }

    private void initData(){
        initMap();
        popupWindow = new EventEditPopupWindow.Builder(this)
                .setTittle("修改活动具体地址（地区、城市默认地图选点区域）")
                .setOnPopConfirm(new EventEditPopupWindow.OnPopConfirm() {
                    @Override
                    public void onConfirm(String et_content) {
                        address = et_content;
                        GeocodeQuery query = new GeocodeQuery(address, city);
                        geocoderSearch.getFromLocationNameAsyn(query);
                        popupWindow.dismiss();
                    }
                })
                .setOnPopConfirm(new EventEditPopupWindow.OnPopCancel() {
                    @Override
                    public void onCancel() {
                        popupWindow.dismiss();
                    }
                })
                .build();
    }

    private void initMap(){
        if (aMap == null) {
            aMap = location_map.getMap();
            aMap.setLocationSource(this);// 设置定位监听
            aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
//            aMap.setMyLocationStyle(AMap.MAP_TYPE_SATELLITE);
            aMap.setMyLocationStyle(new MyLocationStyle());
            aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
            aMap.setOnMapClickListener(this); // 地图点击事件
            aMap.setOnMapLoadedListener(this); // 地图加载完成回调
            // aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);（该方法为老版本的方法，现在不能用了）
            aMap.setOnInfoWindowClickListener(this);
            geocoderSearch = new GeocodeSearch(this);
            geocoderSearch.setOnGeocodeSearchListener(this);
        }
    }

    @Override
    public String getTitleCenter() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.event_location_activity;
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {

    }

    @Override
    public void onMapClick(LatLng latLng) {
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude,latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 20000,GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }

    @Override
    public void onMapLoaded() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                if(TextUtils.isEmpty(place)){
                    Toast.makeText(EventLocationActivity.this,"定位不够精确",Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("address",address);
                intent.putExtra("area",area);
                intent.putExtra("city",city);
                intent.putExtra("place",place);
                intent.putExtra("longtitude",longtitude);
                intent.putExtra("latitude",latitude);
                setResult(LOCATION_RESULT,intent);
                finish();
                break;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                clearMarker();
                mListener.onLocationChanged(aMapLocation);
                LatLng latLng = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
                marker = aMap.addMarker(new MarkerOptions().position(latLng).title(aMapLocation.getAddress()));
                marker.showInfoWindow();
                mlocationClient.stopLocation();
                LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 20000, GeocodeSearch.AMAP);
                geocoderSearch.getFromLocationAsyn(query);
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode()+ ": " + aMapLocation.getErrorInfo();
                LogUtils.logE("AmapErr "+errText);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        location_map.onDestroy();
        if(null != mlocationClient){
            mlocationClient.onDestroy();
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        clearMarker();
        LogUtils.logE("latLonPoint" + regeocodeResult.getRegeocodeAddress().getCity()
                + regeocodeResult.getRegeocodeAddress().getProvince()
            + regeocodeResult.getRegeocodeAddress().getRoads().get(0).getDirection()
                + regeocodeResult.getRegeocodeAddress().getFormatAddress());

        LatLonPoint point = regeocodeResult.getRegeocodeQuery().getPoint();
        LatLng latLng = new LatLng(point.getLatitude(),point.getLongitude());
        marker.destroy();
        marker = aMap.addMarker(new MarkerOptions().position(latLng).title(regeocodeResult.getRegeocodeAddress().getFormatAddress()));
        marker.showInfoWindow();
        address = regeocodeResult.getRegeocodeAddress().getProvince() + regeocodeResult.getRegeocodeAddress().getCity()+
                regeocodeResult.getRegeocodeAddress().getDistrict() + regeocodeResult.getRegeocodeAddress().getTownship();
        area = regeocodeResult.getRegeocodeAddress().getProvince();
        city = regeocodeResult.getRegeocodeAddress().getCity();
        place = regeocodeResult.getRegeocodeAddress().getTownship()+
                regeocodeResult.getRegeocodeAddress().getTowncode()+
                regeocodeResult.getRegeocodeAddress().getNeighborhood()+
                regeocodeResult.getRegeocodeAddress().getBuilding();
        longtitude = regeocodeResult.getRegeocodeQuery().getPoint().getLongitude()+"";
        latitude = regeocodeResult.getRegeocodeQuery().getPoint().getLatitude()+"";

        LogUtils.logE("onRegeocodeSearched  address:" + address +
                "  area:" + area +
                "  city:" + city +
                "  place:" + place +
                "  longtitude:" + longtitude +
                "  latitude:" + latitude);

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        LogUtils.logE("onGeocodeSearched city: " + geocodeResult.getGeocodeQuery().getCity() +
                " getLocationName: " + geocodeResult.getGeocodeQuery().getLocationName() +
                " getProvince: " + geocodeResult.getGeocodeAddressList().get(0).getProvince()+
                " getCity: " +  geocodeResult.getGeocodeAddressList().get(0).getCity() +
                " getFormatAddress: " + geocodeResult.getGeocodeAddressList().get(0).getFormatAddress() +
                " getAdcode: " + geocodeResult.getGeocodeAddressList().get(0).getAdcode() +
                " getBuilding: " + geocodeResult.getGeocodeAddressList().get(0).getBuilding() +
                " getDistrict: " + geocodeResult.getGeocodeAddressList().get(0).getDistrict() +
                " getTownship: " + geocodeResult.getGeocodeAddressList().get(0).getTownship()
        );
        LatLonPoint latLonPoint = new LatLonPoint(geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint().getLatitude()
                ,geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint().getLongitude());
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 20000,GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }

    private void clearMarker(){
        List<Marker> markers = aMap.getMapScreenMarkers();
        for(int j = 0; j < markers.size();j++){
            Marker marker1 = markers.get(j);
            marker1.remove();
        }
        aMap.invalidate();
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        LogUtils.logE("onInfoWindowClick" + marker.getTitle());
        popupWindow.showPopAsLocation(location_map,0,-100, Gravity.CENTER);
    }
}
